package com.aitao.beans;

import com.aitao.enums.MimeType;
import org.apache.tika.Tika;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.util.Objects;

/**
 * 抽象文件类
 *
 * @Company QAX
 * @Author : admin
 * @Create : 2022/1/26 11:17
 */
public abstract class AbstractFile implements IFile {
    private final File globFile;

    public AbstractFile(CharSequence pathname) {
        Objects.requireNonNull(pathname);
        globFile = new File(pathname.toString());
    }

    public AbstractFile(CharSequence parent, CharSequence child) {
        Objects.requireNonNull(parent);
        Objects.requireNonNull(child);
        globFile = new File(parent.toString(), child.toString());
    }

    public AbstractFile(File parent, CharSequence child) {
        Objects.requireNonNull(parent);
        if(!parent.exists()){
            throw new IllegalArgumentException("File is not exists");
        }
        Objects.requireNonNull(child);
        globFile = new File(parent, child.toString());
    }

    public AbstractFile(URI uri) {
        globFile = new File(uri);
    }

    @Override
    public boolean isLegal() {
        if (this == null) {
            return false;
        }
        return globFile.exists();
    }

    @Override
    public long getSize() throws IOException {
        return Files.size(globFile.toPath());
    }

    @Override
    public InputStream toInputStream() throws IOException {
        return Files.newInputStream(globFile.toPath());
    }

    @Override
    public String getExtensionName() {
        String[] splitArray = globFile.getName().split("\\.");
        if (splitArray.length > 1) {
            return splitArray[1];
        }
        return globFile.getName();
    }

    @Override
    public MimeType getMimeType() {
        return MimeType.getInstance(getType());
    }

    public String getType() {
        try {
            return new Tika().detect(globFile);
        } catch (IOException e) {
            throw new RuntimeException("检测文件类型异常");
        }
    }
}
